import { login, logout, getInfo,getMenu } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';

const user = {
	state : {
		token : getToken(),
		name : '',
		account : '',
		avatar : '',
		menus : [],
		roles : [],
	},

	mutations : {
		SET_TOKEN : (state, token) => {
			state.token = token;
		},
		SET_NAME : (state, name) => {
			state.name = name;
		},
		SET_ACCOUNT : (state, account) => {
			state.account = account;
		},
		SET_AVATAR : (state, avatar) => {
			state.avatar = avatar;
		},
		SET_MENUS : (state, menus) => {
			state.menus = menus;
		},
		SET_ROLES : (state, roles) => {
			state.roles = roles;
		}
	},

	actions : {
		// 登录
		Login ({commit}, userInfo) {
			const userName = userInfo.userName.trim();
			return new Promise((resolve, reject) => {
				login(userName, userInfo.password).then(response => {
					const data = response.data;
					setToken(data.token);
					commit('SET_TOKEN', data.token);
					resolve();
				}).catch(error => {
					reject(error);
				});
			});
		},


		// 获取用户信息
		GetInfo ({commit, state}) {
			return new Promise((resolve, reject) => {
				getInfo(state.token).then(response => {
					const data = response.data;
					commit('SET_ACCOUNT', data.account);
					commit('SET_NAME', data.name);
					commit('SET_AVATAR', data.avatar);
					commit('SET_ROLES', data.roles);
					resolve(response);
				}).catch(error => {
					reject(error);
				});
			});
		},
		// 获取用户信息
		GetMenu ({commit, state}) {
			return new Promise((resolve, reject) => {
				getMenu(state.token).then(response => {
					const data = response.data;
					commit('SET_MENUS', data.menu_info);
					resolve(response);
				}).catch(error => {
					reject(error);
				});
			});
		},
		// 登出
		LogOut ({commit, state}) {
			return new Promise((resolve, reject) => {
				logout(state.token).then(() => {
					commit('SET_TOKEN', '');
					commit('SET_ROLES', []);
					removeToken();
					resolve();
				}).catch(error => {
					reject(error);
				});
			});
		},

		// 前端 登出
		FedLogOut ({commit}) {
			return new Promise(resolve => {
				commit('SET_TOKEN', '');
				removeToken();
				resolve();
			});
		}
	}
};

export default user;